//
//  DataBaseSaveEditeImageModel.m
//  WuliHanhan
//
//  Created by tang on 16/3/16.
//  Copyright © 2016年 LVpeng. All rights reserved.
//

#import "DataBaseSaveEditeImageModel.h"
#import "Header.h"

#import "FMDB.h"

@interface DataBaseSaveEditeImageModel ()
{
    FMDatabase *db;
//    NSString *fileString;
    
}

@end




@implementation DataBaseSaveEditeImageModel


sloganIntence(DataBaseSaveEditeImageModel);




- (void)openDataBase
{
    
    //创建编辑图片数据库
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
//    NSLog(@"%@", documentDirectory);
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"];
    db = [FMDatabase databaseWithPath:dbPath] ;
    if (![db open]) {
        NSLog(@"Could not open db");
        //        return ;
    }
    else
    {
        [db executeUpdate:@"DROP TABLE IF EXISTS EditeImageList"];
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS EditeImageList (ImageName blob, CellIndex integer)"];
    }

}



//插入数据
- (void)insertImage:(NSData *)data withIndex:(NSString *)indexString
{
//    NSLog(@"%@", data);
    
//    dispatch_once_t onceToken = 0;
//    dispatch_once(&onceToken, ^{
    
        BOOL writeIsOK = [db executeUpdate:@"INSERT INTO EditeImageList (ImageName, CellIndex) VALUES (?,?)", data, indexString];
        
//    });
   
    
//    if (writeIsOK)
//    {
//        NSLog(@"成功");
//    }
//    else
//    {
//        NSLog(@"SHIBAI");
//    }
}


//删除
- (void)deletaIMage:(NSString *)indesString
{
    BOOL deletaOK = [db executeUpdate:@"DELETE FROM EditeImageList WHERE CellIndex = ?",indesString];
    
    if (deletaOK)
    {
        NSLog(@"chenggong");
    }
    else
    {
        
    }
}




//获取相册数据库的照片
- (void)rearDataBaseForPhotos:(getDataModel)callBack
{
    NSMutableArray *dataArray = [NSMutableArray new];
    NSMutableArray *nameAY = [NSMutableArray new];
    
    FMResultSet *rs = [db executeQuery:@"SELECT CellIndex , ImageName FROM EditeImageList"];
    
//    NSLog(@"%@", rs);
    
    while ([rs next]) {
         NSString *name = [rs stringForColumn:@"CellIndex"];
        [nameAY addObject:name];
//        NSLog(@"")
         NSData *data = [rs dataForColumn:@"ImageName"];
        [dataArray addObject:data];
     }

    callBack(nameAY, dataArray);
//    [self closeDataBase];
}




//拍照结束添加图片index加1
- (void)updateDataBaseWithIndex
{
    [db executeUpdate:@"UPDATE EditeImageList SET CellIndex = CellIndex + 1"];
}



- (void)closeDataBase
{
    [db close];
}






@end
